package com.itheima.stock.secuity.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @author: siwukun
 * @date: 2022/06/15
 * @description:
 */
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 定义权限拒绝的处理器
     * @param request
     * @param response
     * @param accessDeniedException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("text/html;charSet=UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        final HashMap<String, Object> map = new HashMap<>();
        map.put("date",new Date());
        map.put("ex",accessDeniedException.getMessage());
        response.getWriter().write(new ObjectMapper().writeValueAsString(map));
    }
}
